package com.pro01.apirednote.mapper;

import com.pro01.apirednote.dto.CommentResponse;
import com.pro01.apirednote.pojo.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommentMapper {

    // 用户发布评论
    @Insert("INSERT INTO comments (content_id, user_id, parent_id, text, created_at, is_deleted) " +
            "VALUES (#{contentId}, #{userId}, #{parentId}, #{text}, NOW(), false)")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertComment(Comment comment);

    // 查看评论列表
    @Select("SELECT c.id, c.user_id, u.username, c.text, c.created_at, c.parent_id " +
            "FROM comments c JOIN users u ON c.user_id = u.id " +
            "WHERE c.content_id = #{contentId} AND c.is_deleted = false " +
            "ORDER BY c.created_at DESC " +
            "LIMIT #{offset}, #{limit}")
    List<CommentResponse> getCommentsByContentId(@Param("contentId") Long contentId,
                                                 @Param("offset") int offset,
                                                 @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM comments " +
            "WHERE content_id = #{contentId} AND is_deleted = false")
    Long countCommentsByContentId(@Param("contentId") Long contentId);

    // 删除评论
    @Update("UPDATE comments SET is_deleted = true " +
            "WHERE id = #{commentId} AND (user_id = #{userId} OR #{isAdmin} = true)")
    int deleteCommentById(@Param("commentId") Long commentId,
                          @Param("userId") Long userId,
                          @Param("isAdmin") boolean isAdmin);

    @Select("SELECT content_id FROM comments WHERE id = #{commentId}")
    Long findContentIdByCommentId(Long commentId);

    // 获取评论数量
    @Select("SELECT COUNT(*) FROM comments WHERE content_id = #{contentId} AND is_deleted = FALSE")
    int countByContentId(@Param("contentId") Long contentId);


}